/*
 * @Author: zulezhe
 * @Date: 2022-03-25 16:37:39
 * @LastEditors: zulezhe
 * @LastEditTime: 2022-03-28 10:34:51
 * @Path: https://gitee.com/zulezhe/
 * @Description: axios请求二次封装
 */
import axios from "axios";
import Qs from "qs";
import { getToken,removeToken } from "./auth.js";
import {tansParams,blobValidate} from './index.js'
import { ElMessage, ElNotification,ElLoading} from "element-plus";
import { saveAs } from 'file-saver'
//引入router
import router from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_API_PREFIX, // url = base url + request url
  timeout: 5000, // request timeout
});

/**
 * 请求拦截器
 */
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    const token = getToken();
    if (token && !isToken) {
      config.headers["Authorization"] =  token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);
/**
 * 响应拦截器
 */
service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }
    if (code === 401) {
      removeToken()
      router.push("/loginText");
      return Promise.reject(res.data);
    } else if (code === 500) {
      return Promise.reject(res.data);
    } else if (code !== 200) {
      ElNotification.error({
        title: res.data.msg||'系统发出错误',
      });
      return Promise.reject(res.data);
    } else {
      return res.data;
    }
  },
  (error) => {
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    //  else if (message.includes("Request failed with status code")) {
    //   message = "系统接口" + message.substr(message.length - 3) + "异常";
    // }
    ElMessage({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    console.error(error);
    return Promise.reject();
  }
);

function http(config) {
  if (config.method.toLowerCase() === "get") {
    config.params = config.data;
  }
  return service(config);
}
let downloadLoadingInstance;
// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
	  ElMessage({
	    message:errMsg,
	    type: "error",
	    duration: 5 * 1000,
	  });
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
	ElMessage({
	  message: '下载文件出现错误，请联系管理员！',
	  type: "error",
	  duration: 5 * 1000,
	});
    downloadLoadingInstance.close();
  })
}

export default http;
